import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'

import * as userInfoActionsFromOtherFile from '../../actions/userinfo'
import Header from "../../components/Header";
import LoginComponent from '../../components/Login'

class Login extends React.Component {
  constructor(props, context){
    super(props, context);
    this.state = {
      checking: true
    }
  }
  render(){
    return (
      <div>
        <Header title="Login"/>
        {
          this.state.checking
            ? <div>{/**/}</div>
            : <LoginComponent loginHandle={this.loginHandle.bind(this)}/>
        }
      </div>
    );
  }
  componentDidMount(){
    this.doCheck();
  }
  // 登录成功之后的处理
  loginHandle(username){
    // business logical after logining
    // save username
    const actions = this.props.userInfoActions;
    let userinfo = this.props.userinfo;
    userinfo.username = username;
    actions.update(userinfo);

    // 跳转链接
    const params = this.props.match.params;
    const router = params.router;
    if (router) {
      // 跳转到指定的页面
      this.props.history.push(router);
    } else{
      this.goUserPage();
    }
  }
  doCheck(){
    const userinfo = this.props.userinfo;
    if(userinfo.username){
      // has logined
      this.goUserPage();
    } else {
      // not yet logined
      this.setState({
        checking: false
      })
    }
  }
  goUserPage(){
    this.props.history.push('/User');
  }
}

// -----------redux react 绑定 --------------
function mapStateToProps(state) {
  return {
    userinfo: state.userinfo
  }
}

function mapDispatchToProps(dispatch) {
  return {
    userInfoActions: bindActionCreators(userInfoActionsFromOtherFile, dispatch)
  }
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Login);
